<template>
    <van-row>
        <van-col span="2">
            <van-nav-bar left-arrow @click-left="onClickLeft" :border="false" />
        </van-col>
        <van-col span="2">
            <van-icon name="wap-home-o" size="24px" class="icons" @click="onHome" />
        </van-col>
        <van-col span="16">
            <p style="font-size: 14px;text-align: center;font-weight: 800;">搜索页面</p>
        </van-col>
        <van-col span="2">
            <van-icon name="search" size="24px" class="icons" />
        </van-col>
        <van-col span="2">
            <van-icon name="bars" size="24px" class="icons" />
        </van-col>
    </van-row>
    <van-search v-model="keyword" placeholder="请输入搜索关键词" wrap-with-form show-action @search="onSearch"
        @cancel="onCancel" @input="handleInput" />

    <!--这是搜索后的展示内容-->
    <!--当输入框内没有 内容的时候 是不会显示 商品信息的-->
    <div class="container" v-if="keyword.trim().length">
        <span style="border-bottom: 3px solid #d87336; padding-left: 3px;">新车</span>
        <van-swipe-cell v-for="item in searchResult" :key="item.id">
            <!-- <van-card class="goods-card">
               <img src="https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/947c5d2e325b4090b4aa3088465ef831~480x0.jpg" alt="">
            </van-card> -->
            <!-- <img src="https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/947c5d2e325b4090b4aa3088465ef831~480x0.jpg" alt=""> -->

            <van-row>
                <van-col span="8">
                    <van-image width="8rem" height="6rem" :src="item.carimg" />
                </van-col>
                <van-col span="16">
                    <div style="font-weight: 800; margin-top: 10px;">{{ item.carname }}</div>
                    <div style="font-size: 13px; color: red; margin-top: 4px;">{{ item.minprice }}-{{ item.maxprice }}万
                    </div>
                    <div style="font-size: 10px; color: #8c8c89;">
                        <van-icon name="new-arrival-o" size="10px" color="red" />
                        新品上市热点咨询
                    </div>
                </van-col>

            </van-row>


        </van-swipe-cell>
    </div>
    <!--历史记录-->
    <div class="ls-container" v-if="searchHistory.length">
        <div class="ls-header">
            <span style="border-bottom: 3px solid #d87336; padding-left: 3px;">历史记录</span>
            <div class="ls-content">
                <van-tag v-for="(item,index) in searchHistory" :key="item.id" closeable size="medium" @close="closedestrory(index)">
                    {{ item }}
                </van-tag>
            </div>
        </div>
        <van-button type="default"  @click="clearHistory" style="font-size: 13px; 
        color: #666;height: 24px;margin-left: 140px;">清楚全部历史记录</van-button>
    </div>
    <!--汽车推荐-->
    <div v-if="keyword == ''">
         <span style="border-bottom: 3px solid #d87336; padding-left: 3px;">热门推荐</span>
          <van-swipe-cell v-for="(item,index) in productData" :key="index">
            <van-row>
                <van-col span="8">
                    <van-image width="8rem" height="6rem" :src="item.carimg" />
                </van-col>
                <van-col span="16">
                    <div style="font-weight: 800; margin-top: 10px;">{{item.carname}}</div>
                    <div style="font-size: 13px; color: red; margin-top: 4px;">{{item.minprice}}-{{item.maxprice}}万
                    </div>
                    <div style="font-size: 10px; color: #8c8c89;">
                        <van-icon name="new-arrival-o" size="10px" color="red" />
                        新品上市热点咨询
                    </div>
                </van-col>

            </van-row>


        </van-swipe-cell>
    </div>
    
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
//引入api接口
import { CarProductApi } from '../api'

// 输入内容
const keyword = ref('')
//1、定义搜索结果列表存储集
const searchResult = ref([])

// 定义搜索历史记录变量
const searchHistory = ref([])

//保存历史记录

const saveHistory = (keyword)=>{
    // 判断当前关键字是否已经存在于历史记录中
   const index = searchHistory.value.findIndex(item => item === keyword)
   if (index !== -1) searchHistory.value.splice(index, 1)
   // 将关键字添加到数据最前方
   searchHistory.value.unshift(keyword)
   // 限制 历史记录10条
   if (searchHistory.value.length > 10) {
    // 删除最后一个元素

       searchHistory.value.pop()
   }
   // 将历史记录保存到本地存储中
    // lengthenStorage('searchHistory', searchHistory.value)
    localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))

}
// 搜索按钮
const onSearch = (val) => {
    console.log(val);
    const currentKeyword = val.trim()
   if(currentKeyword != ''){
    saveHistory(currentKeyword)
   }
}
// 处理搜索输入
const handleInput =()=>{
    const currentKeyword = keyword.value.trim()
    if(currentKeyword === ''){
        searchResult.value = []
        
    }
}
// 删除全部数据
const clearHistory = () =>{
    searchHistory.value = []
    localStorage.removeItem('searchHistory')
}



//取消按钮
const onCancel = () => {
    console.log("取消");
    keyword.value = ''

}

// 2、监听事件
watch(keyword, (newVal) => {
    const keyword = newVal.trim()
    if (keyword) {
        mockSearch(keyword)
    } else {
        // 清空搜索结果列表
        searchResult.value = []
    }
})

// 模拟数据请求
const mockSearch = (keyword) => {
    //实例数据
    const mockData = [
        { id: 101, name: '北京奔驰-奔驰E级', minprice: '28.89', maxprice: '38.98', img: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/9b08b1c3602645d7ad7574aeb71b6ce3~480x0.jpg' },
        { id: 102, name: '北京奔驰-奔驰C级', minprice: '21.89', maxprice: '26.98', img: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/e8abf034d5504085a9850c7b7632b065~480x0.jpg' },
        { id: 103, name: '北京奔驰-奔驰S级', minprice: '128.89', maxprice: '138.98', img: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/8c904b55208540b3bb0caad827b8226f~480x0.jpg' },
        { id: 104, name: '路虎(进口)-揽胜', minprice: '128.89', maxprice: '138.98', img: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/08ce9dde46f64638aa4df622ce69b497~480x0.jpg' },
        { id: 105, name: '华晨宝马-宝马5系', minprice: '32.89', maxprice: '40.98', img: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/3964028127a0462c97d2611cd8e1a0a1~480x0.jpg' },
        { id: 106, name: '奔驰(进口)-奔驰S级', minprice: '76.26', maxprice: '88.98', img: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/947c5d2e325b4090b4aa3088465ef831~480x0.jpg' }

    ]
    CarProductApi.select.call({carname:keyword}).then(res=>{
        console.log(res);
        searchResult.value= res.filter(item => item.carname.toLowerCase().includes(keyword.toLowerCase()))
        console.log(searchResult.value);
})
    //模拟搜索逻辑
    // const result = mockData.filter(item => item.name.includes(keyword))
    // console.log(result);


    // //更新搜索结果列表
    // searchResult.value = result
    // console.log(searchResult.value);


}

onMounted(()=>{
    CallProductApi()
})

const productData=ref([])
//后台接口对接
const CallProductApi = ()=>{
    CarProductApi.select.call().then(res=>{
        console.log(res);
        productData.value= res
        
    })
}

const onHome = () => {
    // window.location.href ="/moveCar"
    router.push({ name: 'moveCar' })
}

 const closedestrory = (index) => {
      console.log(index);
      searchHistory.value.splice(index, 1)
      localStorage.removeItem('searchHistory')
    };

// 返回上一层页面
const onClickLeft = () => history.back();
</script>

<style scoped>
/* 按钮样式 */
:deep(.van-nav-bar .van-icon) {
    color: black;
    font-size: 24px;
    width: 4px;
}

.icons {
    margin-top: 10px;
    margin-left: 5px;
    cursor: pointer;
}
</style>